﻿using BasicData.Domain;
using BasicData.ErrorCode;
using BasicData.Infastruucture;
using BasicData.Write.API.application.Command.Permission;
using MediatR;

namespace BasicData.Write.API.application.CommandHandler.Permission
{
    public class AddPermissionRoleCommandHandler : IRequestHandler<AddPermissionRoleCommand, ApiResult<object>>
    {
        private readonly IBaseRepository<RolePermissionModel> roleperRepo;

        public AddPermissionRoleCommandHandler(IBaseRepository<RolePermissionModel> roleperRepo)
        {
            this.roleperRepo = roleperRepo;
        }
        public Task<ApiResult<object>> Handle(AddPermissionRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<object> res = new ApiResult<object>();
            List<RolePermissionModel> rolePermissionModel = roleperRepo.GetAll().Where(o => o.RoleId == request.RoleId).ToList();
            int a = 0, b = 0;
            if (rolePermissionModel != null)
            {
                foreach (var item in rolePermissionModel)
                {
                    item.IsDeleted = true;
                    a = roleperRepo.Update(item);
                }
            }
            string[] ids = request.PermissionId.Split(',');
            foreach (string id in ids)
            {
                RolePermissionModel rolePermission = new RolePermissionModel();
                rolePermission.RoleId = request.RoleId;
                rolePermission.PermissionId = Convert.ToInt32(id);
                b = roleperRepo.Create(rolePermission);
            }
            if (b > 0)
            {
                res.Code = BaseEnums.Success;
                res.Msg = "角色权限添加成功";
                res.Data = a;
            }
            else
            {
                res.Code = BaseEnums.Failed;
                res.Msg = "角色权限添加失败";
                res.Data = a;
            }
            return Task.FromResult(res);
        }
    }
}
